package com.yw.atp.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.yw.atp.model.Apps;
import com.yw.atp.model.Group;
import com.yw.atp.service.PersistenceService;
import com.yw.atp.util.StringUtil;
import com.yw.atp.web.ActionBase;

@Scope("prototype")
@Component("appsAction")
public class AppsAction extends ActionBase implements ServletRequestAware{
	private static final long serialVersionUID = 1L;
	@Autowired
	private PersistenceService service;
	HttpServletRequest request;
	private Apps app;
	List<Apps> appList;
	private String res;
	private int start  = 0;
	private int limit  = 20;
	private String ids;
	
	public String list(){
		try {
			JSONObject js = new JSONObject();
			appList = service.findAll(Apps.class);
			if(appList!=null&&appList.size()>0){
				js.put("totalCount",appList.size());
				int len = appList.size();
				start = start>(len-1)?(len-1):start;
				limit = limit>(len-start)?(len):(start+limit);
				js.put("topics",Apps.capture(appList.subList(start,limit)));
			}
			res = js.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String add(){
		if(StringUtil.checkApps(app)){
			if(app.getId()!=null&&app.getId().intValue()>0){
				app.setUpdateAt(new Date());
			}else{
				app.setCreatedAt(new Date());
			}
			service.save(app);
			return SUCCESS;
		}
		return INPUT;
	}
	
	public String del(){
		if(ids!=null&&!"".equals(ids)){
			service.remove(Apps.class.getName(),ids);
		}
		return SUCCESS;
	}
	
	public void setServletRequest(HttpServletRequest request) {
        if(request==null){
            request = ServletActionContext.getRequest();
        }
        this.request = request;
    }
	
	public Apps getApp() {
		return app;
	}

	public void setApp(Apps app) {
		this.app = app;
	}
	
	public List<Apps> getAppList() {
		return appList;
	}

	public void setAppList(List<Apps> appList) {
		this.appList = appList;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getRes() {
		return res;
	}

	public void setRes(String res) {
		this.res = res;
	}

	public PersistenceService getService() {
		return service;
	}

	public void setService(PersistenceService service) {
		this.service = service;
	}
}
